//
//  TSSectionListViewController.m
//  chart
//
//  Created by xu on 15/9/12.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSSectionStatisticListViewController.h"
#import "TSSectionUserModel.h"
#import "RATreeView.h"
#import "RADataObject.h"
#import "TSUserViewController.h"
#import "TSMultipleCheckCell.h"
#import "TSWebViewController.h"
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


@interface TSSectionStatisticListViewController () <RATreeViewDelegate, RATreeViewDataSource>

@property (strong, nonatomic) NSArray *data;
@property (strong, nonatomic) id expanded;
@property (weak, nonatomic) RATreeView *treeView;
@end

@implementation TSSectionStatisticListViewController{
    TSSectionUserModel *rootSectionModel;
    TSSectionUserModel *singleSectionModel;
    NSMutableArray *rootSectionList;
    NSMutableArray *ids;
    NSMutableArray *sections;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    ids = [[NSMutableArray alloc] initWithCapacity:1];
    sections = [[NSMutableArray alloc] initWithCapacity:1];
    WS(weakSelf);
    
    [self leftBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"nav_dark_close"] barHltImage:nil action:^{
        if (!weakSelf) {
            return;
        }
        
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [self rightBarButtonWithTitle:@"统计" barNorImage:nil barHltImage:nil action:^{
        if (!weakSelf) {
            return;
        }
        [weakSelf statistic:rootSectionList];
        //todo 跳转
        
        NSString * idstr = [NSString stringWithFormat:@""];
        
        for (int  i = 0; i < [ids count] ; i ++ ) {
            idstr  = [[idstr stringByAppendingString:[ids objectAtIndex:i]] stringByAppendingString:@","];
        }
        if(idstr.length>0){
            idstr = [idstr substringWithRange:NSMakeRange(0, [idstr length] - 1)];
        }
        NSString * sectionstr = [NSString stringWithFormat:@""];
        
        for (int  i = 0; i < [sections count] ; i ++ ) {
            sectionstr  = [[sectionstr stringByAppendingString:[sections objectAtIndex:i]]
                           stringByAppendingString:@","];
        }
        if(sectionstr.length>0){
            sectionstr = [sectionstr substringWithRange:NSMakeRange(0, [sectionstr length] - 1)];
        }
        TSWebViewController *web_vc=[[TSWebViewController alloc] initWithTitle:@"日程统计" andUrl:[NSString stringWithFormat:@"%@&id=%@&section=%@&userName=%@",kRequestUrl_Journal_outList_statistic, idstr,sectionstr,[TSUserModel sharedInstance].userName]];
        [self.navigationController pushViewController:web_vc animated:YES];
    }];
    
    self.navigationItem.title =@"日程统计";
    
    RATreeView *treeView = [[RATreeView alloc] initWithFrame:CGRectMake(0, 0, currentDeviceWidth, CGRectGetHeight(self.view.bounds)-104.f)];
    
    treeView.delegate = self;
    treeView.dataSource = self;
    treeView.separatorStyle = RATreeViewCellSeparatorStyleSingleLine;
    
    [treeView reloadData];
    [treeView setBackgroundColor:UIColorFromRGB(0xF7F7F7)];
    
    self.treeView = treeView;
    [self.view addSubview:treeView];
    
    /* 加入root部门列表 */
    rootSectionModel = [[TSSectionUserModel alloc] init];
    rootSectionModel.requestParams = @{TSDictionaryKeyDefine_Id:@(1)};
    [rootSectionModel fetchWithPath:kRequestUrl_Journal_outList_pointList_section completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [weakSelf assembleRootSectionList];
        }
    } NoProgress:NO];
}

/*统计*/
-(void)statistic:(NSArray *)array
{
    for(RADataObject *data in array){
        if(data.children){
            [self statistic:data.children];
        }
        if(data.isSelected){
            if(data.type == TSSectionUserItemModel_Type_User){
                if(![ids containsObject:data.sectionId]){
                    [ids addObject:data.sectionId];
                }
            }else{
                if(![sections containsObject:data.sectionId]){
                    [sections addObject:data.sectionId];
                }
            }
        }else{
            if(data.type == TSSectionUserItemModel_Type_User){
                if([ids containsObject:data.sectionId]){
                    [ids removeObject:data.sectionId];
                }
            }else{
                if([sections containsObject:data.sectionId]){
                    [sections removeObject:data.sectionId];
                }
            }

        }
    }
}


/* 组装数据 */
- (void)assembleRootSectionList
{
    
    if (rootSectionModel && rootSectionModel.sectionList) {
        RADataObject *section;
        TSSectionUserItemModel *model;
        rootSectionList = [[NSMutableArray alloc] initWithCapacity:1];
        for (int i=0; i<rootSectionModel.sectionList.count; i++) {
            model = [rootSectionModel.sectionList objectAtIndex:i];
            section = [RADataObject dataObjectWithName:model.userId Name:model.name Type:model.type.integerValue children:nil];
            [rootSectionList addObject:section];
        }
        
        if (rootSectionList.count > 0) {
            self.data = rootSectionList;
            [self.treeView reloadData];
        }
    }
}

- (void)getSectionById:(NSString *)sectionId
{
    WS(weakSelf);
    singleSectionModel = [[TSSectionUserModel alloc] init];
    singleSectionModel.requestParams = @{TSDictionaryKeyDefine_Id:sectionId};
    [singleSectionModel fetchWithPath:kRequestUrl_Journal_outList_pointList_section completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [weakSelf assembleSingleSectionList:sectionId];
        }
    } NoProgress:YES];
}

/* 将请求回来的子部门加入到rootSectionList中 */
- (void)assembleSingleSectionList:(NSString *)sectionId
{
    if (rootSectionList && singleSectionModel) {
        NSArray *new_children = [self createSectionObjects:singleSectionModel.sectionList];
        
        [self appendChildrenToOwnSuperObject:sectionId InArray:rootSectionList AppendChildren:new_children];
        
        [self.treeView reloadData];
    }
}

/* 查询下属部门回来后构造成RADataObject对象 */
- (NSArray *)createSectionObjects:(NSArray *)array
{
    NSMutableArray *objs_arry = [[NSMutableArray alloc] initWithCapacity:1];
    if (array) {
        for (TSSectionUserItemModel *model in array) {
            RADataObject *obj = [[RADataObject alloc] initWithId:model.userId Name:model.name Type:model.type.integerValue children:nil];
            [objs_arry addObject:obj];
        }
        
        return objs_arry;
    }
    
    return nil;
}

- (void)appendChildrenToOwnSuperObject:(NSString *)sectionId InArray:(NSArray *)array AppendChildren:(NSArray *)children
{
    RADataObject *model;
    if (array) {
        for (int i=0; i<array.count; i++) {
            model = [array objectAtIndex:i];
            if ([model.sectionId isEqualToString:sectionId]) {
                model.children = children;
                
                if ([self.expanded isEqual:model]) {
                    [self.treeView collapseRowForItem:model];
                }else{
                    self.expanded = model;
                }
                
                break;
            }
            
            if (model.children) {
                [self appendChildrenToOwnSuperObject:sectionId InArray:model.children AppendChildren:children];
            }
        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

#pragma mark TreeView Delegate methods
- (CGFloat)treeView:(RATreeView *)treeView heightForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 47;
}

- (NSInteger)treeView:(RATreeView *)treeView indentationLevelForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 3 * treeNodeInfo.treeDepthLevel;
}

- (BOOL)treeView:(RATreeView *)treeView shouldExpandItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return YES;
}

- (BOOL)treeView:(RATreeView *)treeView shouldItemBeExpandedAfterDataReload:(id)item treeDepthLevel:(NSInteger)treeDepthLevel
{
    if ([item isEqual:self.expanded]) {
        return YES;
    }
    return NO;
}

- (void)treeView:(RATreeView *)treeView willDisplayCell:(UITableViewCell *)cell forItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    if (treeNodeInfo.treeDepthLevel == 0) {
        cell.backgroundColor = UIColorFromRGB(0xF7F7F7);
    } else if (treeNodeInfo.treeDepthLevel == 1) {
        cell.backgroundColor = UIColorFromRGB(0xD1EEFC);
    } else if (treeNodeInfo.treeDepthLevel == 2) {
        cell.backgroundColor = UIColorFromRGB(0xE0F8D8);
    }
}

#pragma mark TreeView Data Source

- (UITableViewCell *)treeView:(RATreeView *)treeView cellForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    UIButton *ub_view = [self createButton:((RADataObject *)item).isSelected];
    objc_setAssociatedObject(ub_view, "RADataObject", item, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [cell.contentView addSubview:ub_view];
    UILabel *label = [self createLabel:((RADataObject *)item).name];
    [cell.contentView addSubview:label];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (treeNodeInfo.treeDepthLevel == 0) {
        cell.detailTextLabel.textColor = [UIColor blackColor];
    }
    return cell;
}


- (NSInteger)treeView:(RATreeView *)treeView numberOfChildrenOfItem:(id)item
{
    if (item == nil) {
        return [self.data count];
    }
    RADataObject *data = item;
    return [data.children count];
}

- (id)treeView:(RATreeView *)treeView child:(NSInteger)index ofItem:(id)item
{
    RADataObject *data = item;
    if (item == nil) {
        return [self.data objectAtIndex:index];
    }
    return [data.children objectAtIndex:index];
}

- (void)treeView:(RATreeView *)treeView didSelectRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    RADataObject *obj = treeNodeInfo.item;
    
    if (obj.type == TSSectionUserItemModel_Type_Section) {
        if ([self.expanded isEqual:obj]) {
            
        }else{
            if(!obj.children){
                [self getSectionById:obj.sectionId];
            }
        }
    }
    else if (obj.type == TSSectionUserItemModel_Type_User){ // 跳转个人日程页面
        //        TSUserViewController *user_vc = [[TSUserViewController alloc] init];
        //        user_vc.userId = obj.sectionId;
        //
        //        TSBaseNavigationController *nav_vc = [[TSBaseNavigationController alloc] initWithRootViewController:user_vc];
        //
        //        [self.navigationController presentViewController:nav_vc animated:YES completion:nil];
    }
}

- (UIButton *)createButton:(BOOL)isSelected
{
    UIButton *ub_view = [[UIButton alloc] initWithFrame:CGRectMake(MARGIN_LEFT*2, MARGIN_TOP, 30.f, 30.f)];
    [ub_view setBackgroundImage:[UIImage imageNamed:@"cell_not_selected"] forState:UIControlStateNormal];
    [ub_view setBackgroundImage:[UIImage imageNamed:@"cell_selected"] forState:UIControlStateSelected];
    [ub_view addTarget:self action:@selector(ubClick:)
      forControlEvents:UIControlEventTouchUpInside];
    [ub_view setSelected:isSelected];
    return ub_view;
}

-(void)ubClick:(UIButton *)ub_view{
    [ub_view setSelected:!ub_view.isSelected];
    RADataObject *data = objc_getAssociatedObject(ub_view, "RADataObject");
    data.isSelected =ub_view.isSelected;
}

- (UILabel *)createLabel:(NSString *)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(MARGIN_LEFT*6, MARGIN_TOP, currentDeviceWidth-MARGIN_LEFT*7, 30.f)];
    [label setText:title];
    
    return label;
}



@end
